import { t } from 'i18next'
import React, { useEffect, useRef, useState } from 'react'
import { ConfDurationModalWrap } from './style'
import { CheckBox, InnerInputRef, Input, Modal, Select } from '@kedacom/react-next'
import { IVirtualRooms } from '@/api/findVirtualRoom/interface'
import Alert from '@/components/Alert'
import { fetchStatus } from '@/api/global'
import AuthenticationCheck from '@/components/AuthenticationCheck'
import useCreateConfs from '@/hooks/useCreateConfs'
import useCheckAuthentication from '@/components/AuthenticationCheck/useCheckAuthentication'
import { fetchCheckMeetingName } from '@/api/manager/meetingInfoSet'
import { getUTF8ByteCount, regexEnum } from '@/utils'
import { useGlobalStore } from '@/store/global'
/*
会议时长 hour 下拉的数据
*/
const getHourOptions = () => {
	return new Array(25).fill({}).map((_, index) => ({ label: index, value: index }))
}
/*
getMinuteOptions  
根据 hour-select选中的hour，来获得minute-select下拉的数据
*/
const getMinuteOptions = (hour: number) => {
	if (hour === 24) {
		return [{ label: 0, value: 0 }]
	} else {
		return [
			{ label: 0, value: 0 },
			{ label: 15, value: 15 },
			{ label: 30, value: 30 },
			{ label: 45, value: 45 },
		]
	}
}
export interface ConfDurationModalProps {
	isShow: boolean
	setIsShow: (val: boolean) => void
	data: IVirtualRooms | null
}
/*
组件的使用

<ConfDurationModal isShow={isConfModalShow} setIsShow={setIsConfModalShow} data={curData} />
*/
export default function ConfDurationModal(props: ConfDurationModalProps) {
	/*
	props传递的数据
	*/
	const { isShow, setIsShow, data } = props
	/*
	name 会议名称
	*/
	const [name, setName] = useState(data?.name ?? '')
	/*
	hour  hour-select下拉选中的数据
	*/
	const [hour, setHour] = useState(4)
	/*
	minute   minute-select下拉选中的数据
	*/
	const [minute, setMinute] = useState(0)
	/*
	isPermanent 勾选 手动结束  默认不勾选
	选中后，hour-select、minute-select 下拉禁用
	*/
	const [isPermanent, setIsPermanent] = useState(false)
	/*
	minuteOptions 会议时长  分钟的下拉选择数据
	*/
	const [minuteOptions, setMinuteOptions] = useState(getMinuteOptions(hour))
	/*
	inputRef 会议名称ref
	*/
	const inputRef = useRef<InnerInputRef>(null)
	const SWITCH = useGlobalStore((state) => state.SWITCH)

	/*
	useCreateConfs 会议召开
	*/
	const { run } = useCreateConfs()
	/*
	
	*/
	const {
		run: checkAuthentication,
		open: isAuthenticationOpen,
		setOpen: setIsAuthenticationOpen,
		successFn,
	} = useCheckAuthentication()
	/*
	useEffect/ props.data

	1.setName 设置会议名称
	2.setHour 设置 hour-select下拉选中的数据
	3.setMinute 设置 minute-select下拉选中的数据
	4.setIsPermanent 是否手动结束
	*/
	useEffect(() => {
		if (data) {
			setName(data.name)
			setHour(4)
			setMinute(0)
			// 是否手动结束 默认不勾选
			setIsPermanent(false)
		}
	}, [data])

	/*
	handleHourChange hour-select选择的时候的事件

	1.getMinuteOptions 根据选择的hour获得 minute-select 下拉数据
	2.setMinuteOptions 设置 minute-select 下拉数据
	3.setHour 设置 hour-select下拉选中的数据
	*/
	const handleHourChange = (e: React.MouseEvent, val: number) => {
		let _minuteOptions = getMinuteOptions(val)
		setMinuteOptions(_minuteOptions)
		setHour(val)
	}
	/*
	handleMinuteChange minute-select选择的时候的事件
	*/
	const handleMinuteChange = (e: React.MouseEvent, val: number) => {
		setMinute(val)
	}
	/*
	okFn
	弹窗点击确定按钮
	*/
	const okFn = async () => {
		let duration = hour * 60 + minute
		if (duration <= 0 && !isPermanent) {
			Alert(t('会议时长不能为0'))
			return
		}
		let flag = await inputRef.current?.valid()
		if (!flag) {
			Alert(t('请输入正确的会议名称'))
			return
		}
		/*
		fetchStatus
		机房是否托管状态

		export const fetchStatus = async (callback: Function) =>
		*/
		fetchStatus(() => {
			setIsShow(false)
			run(
				{
					create_type: 4,
					template_id: data?.id ?? '',
					duration: isPermanent ? 0 : duration,
					name: name,
				},
				checkAuthentication
			)
		})
	}
	return (
		<>
			<Modal
				className="conf-duration-modal"
				title={t('会议时长')}
				width={428}
				height={300}
				open={isShow}
				okText={t('立即召开')}
				onOk={okFn}
				onCancel={() => {
					setIsShow(false)
				}}
				cancelText={t('取消')}
			>
				<ConfDurationModalWrap>
					<div className="line-wrap">
						<div className="label">{t('会议名称')}</div>
						<Input
							value={name}
							width={200}
							focusMsg={SWITCH.characterLimit ? t('最多32个字符，符号仅限_ - @ . ( ) #') : undefined}
							innerRef={inputRef}
							maxLength={SWITCH.characterLimit ? 32 : undefined}
							rule={{
								required: {
									msg: t('会议名称不能为空'),
								},
								regular: SWITCH.characterLimit
									? [
											{
												regex: regexEnum.nameIllegal,
												msg: t('会议名称存在非法字符，请重新输入'),
											},
											{
												regex: (v) =>
													!/^[\u4e00-\u9fa5A-Za-z0-9]/.test(v) ||
													!/[\u4e00-\u9fa5A-Za-z0-9]$/.test(v),
												msg: t('首尾字符仅允许输入：英文、数字、汉字'),
											},
											{
												regex: async (val) => {
													let flag = await fetchCheckMeetingName({ conf_name: val })
													return !flag
												},
												msg: t('会议名称已存在'),
											},
									  ]
									: [
											{
												regex: (v: string) => {
													let len = getUTF8ByteCount(v)
													return len > 100
												},
												msg: t('输入内容超过长度限制'),
											},
											{
												regex: async (val) => {
													let flag = await fetchCheckMeetingName({ conf_name: val })
													return !flag
												},
												msg: t('会议名称已存在'),
											},
									  ],
							}}
							onChange={(e, v) => {
								setName(v)
							}}
						/>
					</div>
					<div className="line-wrap">
						<div className="label">{t('会议时长')}</div>
						{/* 
						isPermanent  勾选手动结束，hour-select 和 minute-select  禁用  disabled
						*/}
						<Select
							options={getHourOptions()}
							width={64}
							panelMaxItemCount={4}
							value={hour}
							onChange={handleHourChange}
							panelPreventOverflow={false}
							disabled={isPermanent}
						></Select>
						<span className={`hour ${isPermanent ? 'disabled' : ''}`}>{t('小时')}</span>
						<Select
							options={minuteOptions}
							width={64}
							value={minute}
							onChange={handleMinuteChange}
							panelPreventOverflow={false}
							disabled={isPermanent}
						></Select>
						<span className={`minute ${isPermanent ? 'disabled' : ''}`}>{t('分钟')}</span>
					</div>
					<CheckBox
						className="manual-end"
						checked={isPermanent}
						onChange={(e, val) => {
							setIsPermanent(val)
						}}
					>
						{t('手动结束')}
					</CheckBox>
				</ConfDurationModalWrap>
			</Modal>
			{/* 
			AuthenticationCheck 输入动态口令 弹窗
			*/}
			<AuthenticationCheck open={isAuthenticationOpen} setOpen={setIsAuthenticationOpen} callBack={successFn} />
		</>
	)
}
